package com.wuxiaolong.androidmvpsample.ui;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.google.gson.Gson;
import com.wuxiaolong.androidmvpsample.R;
import com.wuxiaolong.androidmvpsample.mvp.main.MainModel;
import com.wuxiaolong.androidmvpsample.mvp.main.MainPresenter;
import com.wuxiaolong.androidmvpsample.mvp.main.MainView;
import com.wuxiaolong.androidmvpsample.mvp.other.MvpActivity;
import com.wuxiaolong.androidmvpsample.retrofit.ApiCallback;
import com.wuxiaolong.androidmvpsample.retrofit.ApiStores;
import com.wuxiaolong.androidmvpsample.retrofit.RetrofitCallback;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;

/**
 * 由Activity/Fragment实现View里方法，包含一个Presenter的引用
 * Created by WuXiaolong on 2015/9/23.
 * github:https://github.com/WuXiaolong/
 * 微信公众号：吴小龙同学
 * 个人博客：http://wuxiaolong.me/
 */
public class MainActivity extends MvpActivity<MainPresenter> implements MainView {

    @Bind(R.id.text)
    TextView text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        initToolBarAsHome("MVP+Retrofit+Rxjava");

    }

    @Override
    protected MainPresenter createPresenter() {
        return new MainPresenter(this);
    }


    @Override
    public void getDataSuccess(MainModel model) {
        //接口成功回调
        Log.d("", "dddd:" + model.getMsg());
        hideLoading();
    }

    @Override
    public void getDataFail(String msg) {
        hideLoading();
        toastShow(msg);
    }


    @OnClick({R.id.button0, R.id.button1, R.id.button2})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button0:
                loadDataByRetrofit();
                break;
            case R.id.button1:
                loadDataByRetrofitRxjava();
                break;
            case R.id.button2:
                //请求接口
//                mvpPresenter.loadDataByRetrofitRxjava("101310222");
                HashMap<String, String> map = new HashMap<>();
//                map.put("version", "1.0");
//                map.put("userId", "yanhao2@wafertest.com");
//                map.put("passWord", "wafer");
//                map.put("clientType", "android");
//                map.put("clientid", "491b315f014b0f58eda3c1e2a401b8c3");
//                map.put("lang", "zh_CN");
                map.put("selectPid", "2c91a0302aa21947012aa2c32b180026");
                map.put("token", "8C667EC08B4CC012B0EE6E964B762791D1BD2374C870E6128241049ABEA6D6D6");
//                File file = new File("");
//                RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
                mvpPresenter.postUserInfo(map);
//                Intent intent = new Intent(
//                        Intent.ACTION_PICK,
//                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//                startActivityForResult(intent, 22);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 22) {
                /**
                 *       list.add(new KeyValue("payeePic", new File(path)));//文件流数据
                 list.add(new KeyValue("mobile", phone));
                 list.add(new KeyValue("wechatId", "wangjin111"));
                 list.add(new KeyValue("salesName", name));
                 list.add(new KeyValue("token", "ssss"));
                 */
                try {
                    Uri originalUri = data.getData();//获得图片的uri
//                        data.getData();
                    ContentResolver resolver = getContentResolver();
                    String[] filePathColumns = {MediaStore.Images.Media.DATA};
                    Cursor c = resolver.query(originalUri, filePathColumns, null, null, null);
                    int columnIndex = c.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    c.moveToFirst();
                    String path = c.getString(columnIndex);
                    c.close();
                    File file = new File(path);
                    Map<String, String> map = new HashMap<>();
//                    map.put("mobile", "15289474330");
//                    map.put("wechatId", "wangjin111");
//                    map.put("salesName", "yanhao");
//                    map.put("token", "222222");
                    map.put("address", "啥发快递");
                    map.put("deviceId", "dddddd22252");
                    map.put("type", "SignComplain");
                    map.put("remark", "事实上对方");
                    RequestBody requestFile1 =
                            RequestBody.create(MediaType.parse("multipart/form-data"), file);
//                    MultipartBody.Part part = MultipartBody.Part.create(requestFile1);
                    Map<String, List<RequestBody>> param = new HashMap<>();
                    List<RequestBody> list = new ArrayList<>();
                    list.add(requestFile1);
                    param.put("fileUpload", list);
                    mvpPresenter.postFilesUser(param, map);
//                    RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
//                    MultipartBody.Part part = MultipartBody.Part.createFormData("payeePic", file.getName(), requestBody);
//                    mvpPresenter.postFileUser(part, map);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void loadDataByRetrofit() {
        showProgressDialog();
//        mvpPresenter.loadDataByRetrofitRxjava("101310222");
        HashMap<String, String> map = new HashMap<>();
        map.put("version", "1.0");
        map.put("userId", "yanhao2@wafertest.com");
        map.put("passWord", "wafer");
        map.put("clientType", "android");
        map.put("clientid", "491b315f014b0f58eda3c1e2a401b8c3");
        map.put("lang", "zh_CN");
//                File file = new File("");
//                RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
//        mvpPresenter.postUserInfo("http://wdev.virsical.cn/saa/login", map);
        Call<String> call = apiStores.userLogin("http://wdev.virsical.cn/saa/login", map);
//        Call<MainModel> call = apiStores.loadDataByRetrofit("http://www.weather.com.cn/adat/sk/101190201.html");
        call.enqueue(new RetrofitCallback<String>() {
            @Override
            public void onSuccess(String model) {
//                dataSuccess(model);
                System.out.println("model:" + model);
                hideLoading();
            }

            @Override
            public void onFailure(int code, String msg) {
                toastShow(msg);
                hideLoading();
            }

            @Override
            public void onThrowable(Throwable t) {
                hideLoading();
                toastShow(t.getMessage());
            }

            @Override
            public void onFinish() {
                hideLoading();
            }
        });
        addCalls(call);
    }

    //全国+国外主要城市代码http://mobile.weather.com.cn/js/citylist.xml
    private void loadDataByRetrofitRxjava() {
        Map<String, String> map = new HashMap<>();
        map.put("selectPid", "2c91a0302aa21947012aa2c32b180026");
        map.put("token", "8C667EC08B4CC012B0EE6E964B762791D1BD2374C870E6128241049ABEA6D6D6");
        mvpPresenter.loadDataByRetrofitRxjava("http://192.168.204.132:8080/Workflow/workflow/workflowInfo/findSelectSubs/", map);
    }

    private void dataSuccess(MainModel model) {
        MainModel.WeatherinfoBean weatherinfo = model.getWeatherinfo();
        String showData = getResources().getString(R.string.city) + weatherinfo.getCity()
                + getResources().getString(R.string.wd) + weatherinfo.getWD()
                + getResources().getString(R.string.ws) + weatherinfo.getWS()
                + getResources().getString(R.string.time) + weatherinfo.getTime();
        text.setText(showData);
    }
}
